class FileUtils {

    getBase64ContentType(base64Data) {
        const parts = base64Data.split(';base64,');
        return parts[0].split(':')[1];
    }

    getBase64Content(base64Data) {
        const parts = base64Data.split(';base64,');
        return parts[1];
    }

    base64ToBlob(base64Data) {
        // 将base64的数据部分提取出来
        const contentType = this.getBase64ContentType(base64Data);
        const raw = window.atob(this.getBase64Content(base64Data));

        // 将原始数据转换为Uint8Array
        const rawLength = raw.length;
        const uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }

        // 使用Uint8Array创建Blob，然后使用Blob创建File
        return new Blob([uInt8Array], {type: contentType});
    }

    base64ToFile(base64Data, filename) {
        const blob = this.base64ToBlob(base64Data);
        const contentType = this.getBase64ContentType(base64Data);
        return new File([blob], filename, {type: contentType});
    }

    fileToBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader()
            reader.onload = (e) => {
                let data
                if (typeof e.target.result === 'object') {
                    data = window.URL.createObjectURL(new Blob([e.target.result]))
                } else {
                    data = e.target.result
                }
                resolve(data);
            }
            reader.onerror = function (error) {
                reject(error);
            };
            //转化为base64
            reader.readAsDataURL(file);

            reader.onerror
        })
    }
}

export default new FileUtils()
